<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header @addTodo="addTodo" />
      <list :todoList="todoList" @delTodo="delTodo" @changeTodo="changeTodo" />
      <Footer @delAll="delAll" @changeAll="changeAll" :todoList="todoList" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "App",
});
</script>

<script setup lang="ts">
import { ref, watch } from "vue";
import { nanoid } from "nanoid";
import Header from "./components/Header/index.vue";
import List from "./components/List/index.vue";
import Footer from "./components/Footer/index.vue";

export interface todoItemType {
  id: string;
  todo: string;
  done: boolean;
}

export type todoListType = todoItemType[];

// const todoList = ref<todoListType>([
//   { id: nanoid(), todo: "抽烟", done: false },
//   { id: nanoid(), todo: "喝酒", done: true },
//   { id: nanoid(), todo: "吹牛逼", done: false },
// ]);
const todoList = ref<todoListType>(
  JSON.parse(localStorage.getItem("todoList")!) || []
);
/**
 * 添加todo
 * @param todo 事件名称
 */
const addTodo = (todo: string) => {
  const newTodo = { id: nanoid(), todo: todo, done: false };
  todoList.value.unshift(newTodo);
  console.log(todoList);
};
/**
 * 删除todo
 * @param index 下标
 */
const delTodo = (index: number) => {
  todoList.value.splice(index, 1);
};
/**
 * 切换单选是否选中
 * @param index 下标
 */
const changeTodo = (index: number) => {
  todoList.value[index].done = !todoList.value[index].done;
};
/**
 * 删除已选中的todo
 */
const delAll = () => {
  todoList.value = todoList.value.filter((item) => !item.done);
};
/**
 *
 * @param type 是否选中
 */
const changeAll = (type: boolean) => {
  todoList.value.forEach((item) => {
    item.done = type;
  });
};
/**
 * 监视属性
 * todolist 发生改变就存储到localStorage里
 */
watch(
  todoList,
  () => {
    localStorage.setItem("todoList", JSON.stringify(todoList.value));
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<style >
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
